Rust - method chaining, iterator
Chaining methods
let new_vec = (1..=10).collect::<Vec<_>>();
println!("{:?}", new_vec);
let my_vec = vec![1,2,3,4,5,6,7,8,9,10];
let new_vec = my_vec.into_iter().skip(3).take(4).collect::<Vec<i32>>();
// 4,5,6,7
iterator
.iter() // iterator of ref
.iter_mut() // iter of mut ref
.into_iter() // consume iter
let vector1 = vec![1,2,3];
let vector1_a = vector1.iter().map(|x| x + 1).collect::<Vec<i32>>();
let vector1_b = vector1.into_iter().map(|x| x * 10).collect::<Vec<i32>>();
// : Vec<i32> 선언하면 뒤에 타입 물고기 안해도됨.
let mut vector2 = vec![10,20,30];
vector2.iter_mut().for_each(|num| *num += 100); // 자체 변환
// into_iter했으므로 vector1은 더이상 사용불가, 메모리인가?
let my_vec = vec!['a','b','거'];
let mut my_vec_iter = my_vec.iter();
assert_eq!(my_vec_iter.next(), &Some('a')); // test
impl iter
#[derive(Debug)]
struct Library {
library_type: LibraryType,
books: Vec<string>
}
#[derive(Debug)]
enum LibraryType {
City,
Country
}
impl Library {
fn add_book(&mut self, book: &str) {
self.books.push(book.to_string());
}
fn new() -> Self {
Self {
library_type: LibraryType::City,
books: Vec::new()
}
}
}
impl Iterator for Library {
type Item = String;
fn next(&mut self) -> Option<String> {
match (self.books.pop()) {
Some(book) => Some(book + "is found!"); // Srting + &str
None => None
}
}
}
fn main() {
let mut my_lib = Library::new();
my_lib.add_book("a");
my_lib.add_book("b");
my_lib.add_book("c");
// item in my_lib 이니까 iterator를 사용
for item in my_lib {
}
}
iter()
할때 mutable type이면 어떻게 되나? 원본을 변형하나? -> iter_mut()